package com.shj.shiro.conf;

import java.util.LinkedHashMap;
import java.util.Map;

import javax.servlet.Filter;

import org.apache.shiro.mgt.DefaultSecurityManager;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class ShiroConfig {

	@Bean
	public ShiroFilterFactoryBean shiroFilter(SecurityManager securityManager) {
		ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();

		shiroFilterFactoryBean.setSecurityManager(securityManager);

		// 会把 spring.mvc.view.prefix + 此处设置的值 + spring.mvc.view.suffix 作为登陆页
		shiroFilterFactoryBean.setLoginUrl("/login");

		// 登录成功后要跳转的链接
		shiroFilterFactoryBean.setSuccessUrl("/index");
		// 未授权界面;
		shiroFilterFactoryBean.setUnauthorizedUrl("/403");
		
		//自定义拦截器
		Map<String, Filter> filters = new LinkedHashMap<String, Filter>();
		
		//filterChain.put("kickout", value);
		shiroFilterFactoryBean.setFilters(filters);
		
		//权限控制
		// anon 表示可以匿名访问 ;  authc 表示需要登陆才可以访问
		Map<String, String> filterChainDefinition = new LinkedHashMap<String, String>();
		
		//配置不会被拦截的链接，顺序判断
		filterChainDefinition.put("/static/**", "anon");
		filterChainDefinition.put("/submitLogin", "anon");
		filterChainDefinition.put("/css/**", "anon");
		filterChainDefinition.put("/js/**", "anon");
		filterChainDefinition.put("/fonts/**", "anon");
		filterChainDefinition.put("/image/**", "anon");
		
		// 配置退出过滤器,其中的具体的退出代码Shiro已经替我们实现了
		filterChainDefinition.put("/logout", "logout");
		
		//加入数据库的配置
		
		
		//配置所有链接均需要登陆。此句需放在最后。因为过滤链是顺序判断的，此句如果放在最上面的话，
		//后面如果有配置可以匿名访问的链接的话，将不会生效。
		filterChainDefinition.put("/**", "authc");
		
		shiroFilterFactoryBean.setFilterChainDefinitionMap(filterChainDefinition);

		return shiroFilterFactoryBean;
	}
	
	@Bean
	public SecurityManager securityManager(AuthRealm authRealm){
		System.out.println("------------ shiro 已加载 -------");
		DefaultSecurityManager manager = new DefaultWebSecurityManager();
		manager.setRealm(authRealm);
		return manager;
	}
	
	@Bean
	public AuthRealm authRealm(){
		return new AuthRealm();
	}
	
}
